package com.zhl.push.util;

import com.zhl.common.vo.Result;
import com.zhl.push.config.WebSocketServer;
import com.zhl.push.model.websocket.entity.WebSocketPush;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * @Title: WebSocketUtils
 * @version： V1.0
 */
@Slf4j
@Component
public class WebSocketUtil {

    /**
     * 发送普通字符串消息
     * @param message
     * @param cid
     */
    public void webSocketMsg(String message, String cid){
        try {
            WebSocketServer.sendInfo(message,cid);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("----------------推送消息失败------------------"+e.getMessage());
        }
    }


    /**
     * 发送Result对象
     * @param result
     * @param cid
     */
    public void webSocketObj(Result result, String cid){
        try {
            WebSocketServer.sendResult(result,cid);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("----------------推送消息失败------------------"+e.getMessage());
        }
    }


    /**
     * websocket推送通用方法
     * @param webSocketPush
     * @return
     */
    public Result websocketPushCommon(WebSocketPush webSocketPush){
        Result result = new Result<>();
        try {
            String model = webSocketPush.getModel();
            Integer pushType = webSocketPush.getPushType();
            Result pushResult = webSocketPush.getResult();
            List<String> idsList = webSocketPush.getIdsList();

            String logInfo = "*******消息推送到部门,对应部门ID为：";
            if(pushType == 2){
                logInfo = "*******消息推送到用户,对应用户ID为：";
            }

            //全局消息推送
            //增加演示部门的推送
//            if(CommonConstant.SOCKET_MODEL_ALARM.equals(model) && pushType == 1){
//                //数据字典查询演示部门的ID
//                List<SysDictItem> dictItem = sysDictItemService.getSysDictItemByDictCode("alert_depart");
//                if(dictItem != null && dictItem.size()>0){
//                    if(idsList == null || idsList.size() == 0){
//                        idsList = new ArrayList<>();
//                    }
//
//                    for (SysDictItem item : dictItem) {
//                        idsList.add(item.getItemValue());
//                    }
//                }
//            }

            if(idsList != null && idsList.size() > 0){
                for (String id : idsList) {
                    log.info(logInfo + id);
                    webSocketObj(pushResult, model + "/" + id);
                }
            }
            result = result.ok("推送成功！");
        }catch (Exception e){
            e.printStackTrace();
            result.error500("推送失败！");
        }
        return result;
    }


}
